#![forbid(unsafe_code)]

// 配置模块
// 最后更新时间：2023-11-08 16:35:00

use thiserror::Error;
use std::collections::HashMap;
use std::sync::RwLock;
use std::string::String;

// 配置错误类型
#[derive(Error, Debug)]
pub enum ConfigError {
    #[error("Key not found")]
    KeyNotFound,
    
    #[error("Invalid value type")]
    InvalidType,
    
    #[error("Config parse failed")]
    ParseFailed,
    
    #[error("Config write failed")]
    WriteFailed,
    
    #[error("Invalid key name")]
    InvalidKey,
}

// 定义结果类型
type ConfigResult<T> = Result<T, ConfigError>;

// 配置值类型枚举
#[derive(Debug, Clone, PartialEq)]
pub enum ConfigValue {
    String(String),
    Bool(bool),
    Uint(u64),
    Int(i64),
    Float(f64),
    Null,
}

impl ConfigValue {
    // 获取字符串值
    pub fn as_string(&self) -> ConfigResult<String> {
        match self {
            ConfigValue::String(s) => Ok(s.clone()),
            _ => Err(ConfigError::InvalidType),
        }
    }
    
    // 获取布尔值
    pub fn as_bool(&self) -> ConfigResult<bool> {
        match self {
            ConfigValue::Bool(b) => Ok(*b),
            _ => Err(ConfigError::InvalidType),
        }
    }
    
    // 获取无符号整数值
    pub fn as_uint(&self) -> ConfigResult<u64> {
        match self {
            ConfigValue::Uint(u) => Ok(*u),
            ConfigValue::Int(i) if *i >= 0 => Ok(*i as u64),
            _ => Err(ConfigError::InvalidType),
        }
    }
    
    // 获取整数值
    pub fn as_int(&self) -> ConfigResult<i64> {
        match self {
            ConfigValue::Int(i) => Ok(*i),
            ConfigValue::Uint(u) => Ok(*u as i64),
            _ => Err(ConfigError::InvalidType),
        }
    }
    
    // 获取浮点数值
    pub fn as_float(&self) -> ConfigResult<f64> {
        match self {
            ConfigValue::Float(f) => Ok(*f),
            ConfigValue::Int(i) => Ok(*i as f64),
            ConfigValue::Uint(u) => Ok(*u as f64),
            _ => Err(ConfigError::InvalidType),
        }
    }
    
    // 检查是否为null
    pub fn is_null(&self) -> bool {
        matches!(self, ConfigValue::Null)
    }
}

// 配置对象
pub struct Config {
    data: HashMap<String, ConfigValue>,
}

impl Config {
    // 创建新的配置对象
    pub fn new() -> Self {
        Config {
            data: HashMap::new(),
        }
    }
    
    // 设置字符串值
    pub fn set_string(&mut self, key: &str, value: &str) -> ConfigResult<()> {
        self.validate_key(key)?;
        self.data.insert(key.to_string(), ConfigValue::String(value.to_string()));
        Ok(())
    }
    
    // 设置布尔值
    pub fn set_bool(&mut self, key: &str, value: bool) -> ConfigResult<()> {
        self.validate_key(key)?;
        self.data.insert(key.to_string(), ConfigValue::Bool(value));
        Ok(())
    }
    
    // 设置无符号整数值
    pub fn set_uint(&mut self, key: &str, value: u64) -> ConfigResult<()> {
        self.validate_key(key)?;
        self.data.insert(key.to_string(), ConfigValue::Uint(value));
        Ok(())
    }
    
    // 设置整数值
    pub fn set_int(&mut self, key: &str, value: i64) -> ConfigResult<()> {
        self.validate_key(key)?;
        self.data.insert(key.to_string(), ConfigValue::Int(value));
        Ok(())
    }
    
    // 设置浮点数值
    pub fn set_float(&mut self, key: &str, value: f64) -> ConfigResult<()> {
        self.validate_key(key)?;
        self.data.insert(key.to_string(), ConfigValue::Float(value));
        Ok(())
    }
    
    // 删除键
    pub fn remove(&mut self, key: &str) -> bool {
        self.data.remove(key).is_some()
    }
    
    // 检查键是否存在
    pub fn has_key(&self, key: &str) -> bool {
        self.data.contains_key(key)
    }
    
    // 获取值
    pub fn get(&self, key: &str) -> ConfigResult<&ConfigValue> {
        self.data.get(key).ok_or(ConfigError::KeyNotFound)
    }
    
    // 获取所有键
    pub fn keys(&self) -> Vec<String> {
        self.data.keys().cloned().collect()
    }
    
    // 清除所有配置
    pub fn clear(&mut self) {
        self.data.clear();
    }
    
    // 获取配置项数量
    pub fn len(&self) -> usize {
        self.data.len()
    }
    
    // 检查是否为空
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }
    
    // 验证键名
    fn validate_key(&self, key: &str) -> ConfigResult<()> {
        if key.is_empty() {
            return Err(ConfigError::InvalidKey);
        }
        
        // 检查键名是否只包含合法字符
        for c in key.chars() {
            if !c.is_alphanumeric() && c != '_' && c != '-' && c != '.' && c != '/' {
                return Err(ConfigError::InvalidKey);
            }
        }
        
        Ok(())
    }
}

// 线程安全配置管理器
pub struct ConfigManager {
    config: RwLock<Config>,
}

impl ConfigManager {
    // 创建新的配置管理器
    pub fn new() -> Self {
        ConfigManager {
            config: RwLock::new(Config::new()),
        }
    }
    
    // 设置字符串值
    pub fn set_string(&self, key: &str, value: &str) -> ConfigResult<()> {
        self.config.write().map_err(|_| ConfigError::WriteFailed)?.set_string(key, value)
    }
    
    // 设置布尔值
    pub fn set_bool(&self, key: &str, value: bool) -> ConfigResult<()> {
        self.config.write().map_err(|_| ConfigError::WriteFailed)?.set_bool(key, value)
    }
    
    // 设置无符号整数值
    pub fn set_uint(&self, key: &str, value: u64) -> ConfigResult<()> {
        self.config.write().map_err(|_| ConfigError::WriteFailed)?.set_uint(key, value)
    }
    
    // 设置整数值
    pub fn set_int(&self, key: &str, value: i64) -> ConfigResult<()> {
        self.config.write().map_err(|_| ConfigError::WriteFailed)?.set_int(key, value)
    }
    
    // 设置浮点数值
    pub fn set_float(&self, key: &str, value: f64) -> ConfigResult<()> {
        self.config.write().map_err(|_| ConfigError::WriteFailed)?.set_float(key, value)
    }
    
    // 获取值
    pub fn get(&self, key: &str) -> ConfigResult<ConfigValue> {
        self.config.read().map_err(|_| ConfigError::ParseFailed)?.get(key).cloned()
    }
    
    // 检查键是否存在
    pub fn has_key(&self, key: &str) -> bool {
        self.config.read().map(|c| c.has_key(key)).unwrap_or(false)
    }
    
    // 删除键
    pub fn remove(&self, key: &str) -> bool {
        self.config.write().map(|mut c| c.remove(key)).unwrap_or(false)
    }
    
    // 清除所有配置
    pub fn clear(&self) {
        self.config.write().map(|mut c| c.clear()).unwrap_or(());
    }
    
    // 获取配置项数量
    pub fn len(&self) -> usize {
        self.config.read().map(|c| c.len()).unwrap_or(0)
    }
    
    // 获取所有键
    pub fn keys(&self) -> Vec<String> {
        self.config.read().map(|c| c.keys()).unwrap_or(Vec::new())
    }
}

// 安全配置对象（用于FFI交互）
pub struct SafeZenrsConfig {
    config: Config,
}

impl SafeZenrsConfig {
    // 创建新的安全配置对象
    pub fn new() -> Self {
        SafeZenrsConfig {
            config: Config::new(),
        }
    }
    
    // 设置字符串值
    pub fn set_string(&mut self, key: &str, value: &str) -> ConfigResult<()> {
        self.config.set_string(key, value)
    }
    
    // 设置布尔值
    pub fn set_bool(&mut self, key: &str, value: bool) -> ConfigResult<()> {
        self.config.set_bool(key, value)
    }
    
    // 设置无符号整数值
    pub fn set_uint(&mut self, key: &str, value: u64) -> ConfigResult<()> {
        self.config.set_uint(key, value)
    }
    
    // 设置整数值
    pub fn set_int(&mut self, key: &str, value: i64) -> ConfigResult<()> {
        self.config.set_int(key, value)
    }
    
    // 设置浮点数值
    pub fn set_float(&mut self, key: &str, value: f64) -> ConfigResult<()> {
        self.config.set_float(key, value)
    }
    
    // 获取字符串值
    pub fn get_string(&self, key: &str) -> ConfigResult<String> {
        self.config.get(key).and_then(|v| v.as_string())
    }
    
    // 获取布尔值
    pub fn get_bool(&self, key: &str) -> ConfigResult<bool> {
        self.config.get(key).and_then(|v| v.as_bool())
    }
    
    // 获取无符号整数值
    pub fn get_uint(&self, key: &str) -> ConfigResult<u64> {
        self.config.get(key).and_then(|v| v.as_uint())
    }
    
    // 获取整数值
    pub fn get_int(&self, key: &str) -> ConfigResult<i64> {
        self.config.get(key).and_then(|v| v.as_int())
    }
    
    // 获取浮点数值
    pub fn get_float(&self, key: &str) -> ConfigResult<f64> {
        self.config.get(key).and_then(|v| v.as_float())
    }
    
    // 检查键是否存在
    pub fn has_key(&self, key: &str) -> bool {
        self.config.has_key(key)
    }
    
    // 删除键
    pub fn remove(&mut self, key: &str) -> bool {
        self.config.remove(key)
    }
    
    // 清除所有配置
    pub fn clear(&mut self) {
        self.config.clear();
    }
    
    // 获取配置项数量
    pub fn len(&self) -> usize {
        self.config.len()
    }
}

// 最后更新时间：2023-11-08 16:35:00